package com.atguigu.sparkstreaming.demos

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}
import redis.clients.jedis.Jedis

/**
 * Created by Smexy on 2022/8/22
 *

 *
 *
 *
 */
object GracefullyStopAppDemo {

  val appName = "wordcountApp"

  def main(args: Array[String]): Unit = {


    val streamingContext = new StreamingContext("local[*]", appName, Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "sz220409test",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> "true"
    )


    val topics = Array("topicD")


    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    val ds1: DStream[(String, Int)] = ds.flatMap(record => record.value().split(" "))
      .map(word => (word, 1))
      .reduceByKey(_ + _)


    ds1.print(1000)

    streamingContext.start()

    //停止的代码只能写在start之后，先启动，再停止。
    //写这里的话，刚启动，就停止了，白起
    //streamingContext.stop()


    //在阻塞main方法之前，启动线程
    val stopThread = new StopAppThread(appName, streamingContext)

    new Thread(stopThread).start()

    streamingContext.awaitTermination()

    //压根没有执行机会的，59行就阻塞main了，无法执行到这步
    //streamingContext.stop()

  }

}

class StopAppThread(name:String,context:StreamingContext) extends Runnable {

  val jedis:Jedis =  new Jedis("hadoop102", 6379)

  //不断地监听是否需要关闭app
  override def run(): Unit = {

    while(!jedis.exists(name)){

      //监听是否需要关闭app
      //如何知道是否需要关闭app，一定需要一个信息传递的媒介(数据库，文件系统)
      //借用redis作为信息传递的媒介。 如果需要关闭app，那么就在redis中新增一个key，key的名字为app的名字，只要key存在，就意味需要关闭，否则不关闭
      Thread.sleep(5000)

    }

    //执行关闭逻辑
    context.stop(true,true)

  }
}
